// // node引入包名
// const iot = require('alibabacloud-iot-device-sdk');
//
// //创建iot.device对象将会发起到阿里云IoT的连接
// const device = iot.device({
//   productKey: 'g8wkTeT5zdj', //将<productKey>修改为实际产品的ProductKey
//   deviceName: 'cyqiot',//将<deviceName>修改为实际设备的DeviceName
//   deviceSecret: '9ef84ea1cc223abd2a15e6cfe4166f90',//将<deviceSecret>修改为实际设备的DeviceSecret
// });
//
//
// //监听connect事件
// device.on('connect', () => {
//   //将<productKey> <deviceName>修改为实际值
//   device.subscribe('/g8wkTeT5zdj/cyqiot/user/get');
//   console.log('connect successfully!');
//   device.publish('/g8wkTeT5zdj/cyqiot/user/update', 'hello world!');
// });
//
// //监听message事件
// device.on('message', (topic, payload) => {
//   console.log(topic, payload.toString());
// });
const crypto = require('crypto');
const mqtt = require('mqtt');
    let start = '',
        flag;//开关状态，实现同步
//设备身份三元组+区域
const deviceConfig = {
    productKey: "a1MygIF2eyN",
    deviceName: "cyqtest",
    deviceSecret: "877d1e26542108293b3d6e5b44177933",
    regionId: "cn-shanghai"
};
//根据三元组生成mqtt连接参数
const options = initMqttOptions(deviceConfig);
const url = `tcp://${deviceConfig.productKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuncs.com:1883`
// console.log("url:"+url)
//2.建立连接
const client = mqtt.connect(url, options);
console.log("设备连接成功")
setInterval(function() {
             const data = getPostData() //获取数据
             console.log("开始上传："+data)
                  // client.publish(topic2, JSON.stringify({status:1}));
    //发布数据到topic
        client.publish(topic, data);
    }, 10* 1000);
//3.设备事件上报
// const topic2 = `/sys/a1MygIF2eyN/${deviceConfig.deviceName}/thing/event/status/post`
//4.属性数据上报
const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;
client.on('message', function(topics, message) {
    //
    // // console.log(topics)
    // //服务topic
    // if (topics === '/sys/a1MygIF2eyN/cyqtest/thing/service/switch'){
    //         // console.log("topic " + topics)
    //      // console.log("message " + message)
    // const obj  = JSON.parse(message);
    // const a = obj.params;//解析云端数据
    //     flag = a.switch;//获取云端开关状态
    // if (flag){
    //     console.log("接收到云端指令，准备上传数据...")
    //      start = setInterval(function() {
    //          const data = getPostData() //获取数据
    //          console.log("开始上传："+data)
    //               // client.publish(topic2, JSON.stringify({status:1}));
    // //发布数据到topic
    //     client.publish(topic, data);
    // }, 10* 1000);
    //
    // }
    // else {
    //     //通过判断setInterval是否为空，不为空，执行clearInterval并置空，否则可能会造成循环执行
    //     if(start){
    //         console.log("message " + flag)
    //         const payloadJson = {
    //     id: Date.now(),
    //     params: {
    //         isSwitch:flag
    //     },
    //     method: "thing.event.property.post"
    // }//云端取消接收，最后返回开关状态
    //         client.publish(topic, JSON.stringify(payloadJson));
    //          clearInterval(start);
    //         start = '';
    //          console.log("接收到云端指令，取消上传数据...")
    //     }
    // }
    //
    // }
})
//IoT平台mqtt连接参数初始化
function initMqttOptions(deviceConfig) {
    const params = {
        productKey: deviceConfig.productKey,
        deviceName: deviceConfig.deviceName,
        timestamp: Date.now(),
        clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT参数
    const options = {
        keepalive: 60, //60s
        clean: false, //cleanSession保持持久会话
        protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成客户端clientId，username，password
    options.password = signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=3,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;
    // console.log(options)
    return options;
}
function getPostData() {
    //Math.floor((Math.random() * 20) + 10)
    let wd = (Math.random() * 20 + 10.0),
            Temperature = (Math.random() * 25 + 20.0),
            yanwu = (Math.random() * 30 + 50.0),
            PH = (Math.random() * 14+2.0),
            turbid = (Math.random()*10.0),
            shuiwei  = (Math.random()*100.0),
            JL = (Math.random()*100.0-5.0);
    const payloadJson = {
        id: Date.now(),
        params: {
            wd: wd,
            Temperature: Temperature,
            yanwu:yanwu,
            PH:PH,
            turbid:turbid,
            shuiwei:shuiwei,
            JL:JL,
            isSwitch:flag
        },
        method: "thing.event.property.post"
    }
     // console.log(payloadJson)

    return JSON.stringify(payloadJson);
}

function signHmacSha1(params, deviceSecret) {
    let keys = Object.keys(params).sort();
    // console.log(keys)
    //wdx52ynkgj
    // console.log( "sss:"+Math.random().toString(36).substr(2),)
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
        list.push(`${key}${params[key]}`);
    });
    // console.log(list)
    const contentStr = list.join('');
    // console.log(contentStr)
    //   以设备的 deviceSecret: "877d1e26542108293b3d6e5b44177933",作为加密密钥
    // const sha1 =  crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex')
    // console.log(sha1)
    return crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex');}